<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
        <el-form-item label="创建日期" prop="createdAt">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
          —
          <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="searchInfo.userName" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="商品名" prop="productName">
          <el-input v-model="searchInfo.productName" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="searchInfo.orderNumber" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="微信支付订单号" prop="outTradeNumber">
          <el-input v-model="searchInfo.outTradeNumber" placeholder="搜索条件" />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="searchInfo.status" clearable placeholder="请选择">
            <el-option label="待支付" :value="1" />
            <el-option label="已支付" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="已退款" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付类型" prop="paymentType">
          <el-select v-model="searchInfo.paymentType" clearable placeholder="请选择">
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="云闪付" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">

        <el-button type="danger" icon="delete" @click="onDelete" :disabled="!multipleSelection.length">批量删除</el-button>
        <ExportTemplate
          template-name="order.xlsx"
          template-title="订单信息"
          template-type="order"
          :table-data="tableData"
          :table-headers="[
            { label: 'ID', prop: 'ID', width: '' },
            { label: '创建时间', prop: 'CreatedAt', width: '' },
            { label: '更新时间', prop: 'UpdatedAt', width: '' },
            { label: '订单号', prop: 'orderNumber', width: '' },
            { label: '微信支付订单号', prop: 'outTradeNumber', width: '' },
            { label: '用户ID', prop: 'userID', width: '' },
            { label: '用户名', prop: 'userName', width: '' },
            { label: '商品ID', prop: 'productID', width: '' },
            { label: '商品名', prop: 'productName', width: '' },
            { label: '商品规格', prop: 'productSpecs', width: '' },
            { label: '数量', prop: 'quantity', width: '' },
            { label: '单价', prop: 'unitPrice', width: '' },
            { label: '总金额', prop: 'totalAmount', width: '' },
            { label: '实付金额', prop: 'paidAmount', width: '' },
            { label: '订单状态', prop: 'status', width: '' },
            { label: '支付类型', prop: 'paymentType', width: '' },
            { label: '支付方式', prop: 'paymentMethod', width: '' },
            { label: '支付时间', prop: 'paymentTime', width: '' },
            { label: '备注', prop: 'remark', width: '' },
          ]"
        />
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="日期" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column align="left" label="订单号" prop="orderNumber" width="180" />
        <el-table-column align="left" label="用户名" prop="userName" width="120" />
        <el-table-column align="left" label="商品名" prop="productName" width="200" show-overflow-tooltip />
        <el-table-column align="left" label="规格" prop="productSpecs" width="150" show-overflow-tooltip />
        <el-table-column align="left" label="数量" prop="quantity" width="80" />
        <el-table-column align="left" label="总金额" prop="totalAmount" width="100">
          <template #default="scope">¥{{ scope.row.totalAmount }}</template>
        </el-table-column>
        <el-table-column align="left" label="实付金额" prop="paidAmount" width="100">
          <template #default="scope">¥{{ scope.row.paidAmount }}</template>
        </el-table-column>
        <el-table-column align="left" label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="支付方式" prop="paymentMethod" width="100" />
        <el-table-column align="left" label="支付时间" prop="paymentTime" width="180">
          <template #default="scope">{{ scope.row.paymentTime ? formatDate(scope.row.paymentTime) : '-' }}</template>
        </el-table-column>
        <el-table-column align="left" label="操作" fixed="right" min-width="240">
          <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看详情</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)" :disabled="scope.row.status !== 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

  </div>
</template>

<script setup>
import {
  deleteOrder,
  batchDeleteOrder,
  findOrder,
  getOrderList
} from '@/api/order'
import { formatDate } from '@/utils/format'
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatBoolean, formatDate as formatDateFunc, filterDict } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

defineOptions({
  name: 'Order'
})



const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }
  ],
})


const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getOrderList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{

}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrderFunc(row)
  })
}

// 多选删除
const onDelete = async() => {
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据'
    })
    return
  }
  
  // 检查是否有非未支付状态的订单
  const nonPendingOrders = multipleSelection.value.filter(item => item.status !== 1)
  if (nonPendingOrders.length > 0) {
    ElMessage({
      type: 'warning',
      message: '只能删除未支付状态的订单'
    })
    return
  }
  
  ElMessageBox.confirm('确定要删除选中的订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const IDs = multipleSelection.value.map(item => item.ID)
    const res = await batchDeleteOrder({ ids: IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}


// 删除行
const deleteOrderFunc = async (row) => {
  // 检查订单状态，只有待支付状态的订单才能删除
  if (row.status !== 1) {
    ElMessage.warning('只有待支付状态的订单才能删除')
    return
  }
  const res = await deleteOrder({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}




const detailFrom = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findOrder({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data.reorder
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}

// 状态类型映射
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',  // 待支付
    2: 'success',  // 已支付
    3: 'danger',   // 已取消
    4: 'warning'   // 已退款
  }
  return statusMap[status] || 'info'
}

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    1: '待支付',
    2: '已支付',
    3: '已取消',
    4: '已退款'
  }
  return statusMap[status] || status
}

</script>

<style>
</style>